﻿using ApplicationBase.Core.Security;
using Microsoft.AspNetCore.Http;

namespace ApplicationBase.Core.Service.Identity
{
    public class IdentityService : IIdentityService
    {
        private readonly IHttpContextAccessor _context;
        public IdentityService(IHttpContextAccessor context)
        {
            _context = context;
        }

        public long? GetUserId()
        {
            if(_context.HttpContext != null)
            {
                var claim = _context.HttpContext.User.Claims.FirstOrDefault(it => it.Type == CustomClaimType.Id);
                if (claim == null) return null;
                
                long id;
                var canConvert = Int64.TryParse(claim.Value, out id);
                return canConvert ? id : null;
            }
            return null;
        }

        public string? GetUserName()
        {
            if (_context.HttpContext != null)
            {
                var claim = _context.HttpContext.User.Claims.FirstOrDefault(it => it.Type == CustomClaimType.UserName);
                return claim == null ? null : claim.Value;
            }
            return null;
        }

        public List<string>? GetUserRoles()
        {
            if (_context.HttpContext != null)
            {
                var claim = _context.HttpContext.User.Claims.Where(it => it.Type == CustomClaimType.Role).ToList();
                return claim.Count() == 0 ? null : claim.Select(it => it.Value).ToList();
            }
            return null;
        }
    }
}
